package com.heima.user.service.impl;


import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author itheima
 */
@Slf4j
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    @Override
    public ResponseResult login(LoginDto loginDto) {
        // 1.判斷用戶名和密碼都有值，按正常用戶處理
        String pwdIn = loginDto.getPassword();
        if (StringUtils.isNotBlank(pwdIn) && StringUtils.isNotBlank(loginDto.getPhone())) {
            //1.1 判断用户名是否正确
            ApUser apUser = this.getOne(Wrappers.<ApUser>lambdaQuery()
                    .eq(ApUser::getPhone, loginDto.getPhone()));
            if (apUser == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "用户不存在");
            }
            //1.2 比对登录密码与表中的密文密码
            String pwdDb = apUser.getPassword();
            boolean result = BCrypt.checkpw(pwdIn, pwdDb);//BCrypt验证
            //密碼錯誤
            if (!result) {

                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //1.3 生成token
            String token = AppJwtUtil.getToken(apUser.getId().longValue());
            apUser.setPassword("");
            Map map = new HashMap<>();
            map.put("token",token);
            map.put("user",apUser);
            return ResponseResult.okResult(map);
        }else {

            // 2. 按游客处理
            //直接为用户按照0生成TOKEN
            String token = AppJwtUtil.getToken(0L);
            Map map = new HashMap();
            map.put("token", token);

            return ResponseResult.okResult(map);
        }



    }
}
